import React, {PropsWithChildren, useEffect, useMemo, useState} from 'react'
import Scaffold from "./Scaffold";
import EditHomeApplianceForm from "./EditHomeApplianceForm";
import {addOrder, getOrderDetail, updateOrder, UpdateOrderRequest} from "../apis/OrderApi";
import homeApplianceOrderPageStackStore from "../store/HomeApplianceOrderPageStackStore";
import {observer} from 'mobx-react-lite';

export interface EditHomeAppliancePageProps extends PropsWithChildren {
    id?: number
}

const EditHomeAppliancePage: React.FC<EditHomeAppliancePageProps> = ({id}) => {
    const initialValue = homeApplianceOrderPageStackStore.detail

    const [loading, setLoading] = useState(true)
    const isAdd = useMemo(() => {
        return !id
    }, [id]);
    useEffect(() => {
        if (id) {
            getOrderDetail(id).then(response => {
                homeApplianceOrderPageStackStore.setDetail(response.data)
            }).finally(() => {
                setLoading(false)
            })
        } else {
            setLoading(false)
        }
    }, [id]);
    useEffect(() => {
        return () => {
            homeApplianceOrderPageStackStore.setDetail(undefined)
        }
    }, []);
    return <Scaffold title={"编辑家电订单"}>
        {!loading && <EditHomeApplianceForm initialValue={initialValue} onConfirm={async value => {
            const request: UpdateOrderRequest = {
                ...value,
                paymentDateTime: value.paymentDateTime?.toJSON(),
                deliveryDateTime: value.deliveryDateTime?.toJSON()
            }
            if (isAdd) {
                homeApplianceOrderPageStackStore.appendItemByDetail((await addOrder(request)).data)
            } else {
                homeApplianceOrderPageStackStore.updateDetail((await updateOrder(id!!, request)).data)
            }
        }}/>}
    </Scaffold>
}

export default observer(EditHomeAppliancePage)


